﻿using System;
using System.Diagnostics;
using DemoWindowsPhoneMvp.Logic.Messages;
using DemoWindowsPhoneMvp.Logic.Views.Fourth;
using DemoWindowsPhoneMvp.Logic.Views.Second;
using Microsoft.Phone.Reactive;
using Microsoft.Phone.Tasks;
using WindowsPhoneMvp;
using WindowsPhoneMvp.Navigation;

namespace DemoWindowsPhoneMvp.Logic.Views.Main
{
    public class MainPresenter : Presenter<IMainView, MainViewModel>
    {
        public string PersistMe { get; set; }

        public PhotoResult PhotoResult { get; set; }

        public MainPresenter(IMainView view, INavigationService navigationService)
            : base(view, navigationService)
        {
            //Observe Events
            View.Load += ViewLoad;
            
            Observable.FromEvent<EventArgs>(View, "LaunchingCamera")
                .Subscribe(x => StartTask<CameraCaptureTask, PhotoResult>(z => PhotoResult = z));

            //Transient properties
            Transient(() => this).Property(x => x.PersistMe); 
            Transient(x => x.PersistMeToo);

            ApplicationTransientState.Save("GlobalState", "RememberMe");

            Model.NavigatingToViewTwo = Navigate.ByCommand<IView<SecondViewModel>>();
        }

        void ViewLoad(object sender, EventArgs e)
        {
            Model.OnLoaded();
            PersistMe = "test";
            Model.PersistMeToo = "another test";
            TransientState.Save("PageState", "RememberMeOnThisPage");

            Model.ForWidget.SetFromMainPresenter = "Set by the parent presenter";
            Messages.Publish(new HelloMessage{ Monkey = "Message from main presenter!" });
        }

        public void ToViewTwo(object sender, MainViewModel dataContext)
        {
            Navigate.ToView<IView<SecondViewModel>>();
        }

        public void ToViewFour()
        {
            Navigate.ToView<IFourthView>();
        }

        public override void OnActivated()
        {
        }

        public override void OnNavigationTo(NavigationData navigationData)
        {
            Debug.WriteLine("Navigated to " + navigationData.View);
        }

        public override void OnNavigatedFrom(bool isExiting)
        {
            Debug.WriteLine("Navigating from MainPresenter");

            if(isExiting)
                Debug.WriteLine("Exiting app.");
        }
    }
}
